package com.czt.mp3recorder;

import com.czt.mp3recorder.util.LameUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

public class DataEncoderThread2 extends Thread implements IDataEncode{
    private final String TAG = DataEncoderThread2.class.getSimpleName();

    private FileOutputStream mFileOutputStream;
    private byte[] mMp3Buffer;
    private Task mTakeTask = null;
    private boolean shouldQuit = false;

    public DataEncoderThread2(File file, int bufferSize) throws FileNotFoundException {
        this.mFileOutputStream = new FileOutputStream(file);
        mMp3Buffer = new byte[(int) (7200 + (bufferSize * 2 * 1.25))];
    }

    @Override
    public void sendStopMessage() {
        interrupt();
    }

    @Override
    public void addTask(short[] rawData, int readSize) {
        if(!shouldQuit) {
            mTasks.add(new Task(rawData, readSize));
        }
    }

    @Override
    public void run() {
        super.run();
        while (true) {
            try {
                if(shouldQuit && mTasks.size() == 0){
                    break;
                }
                Task task = mTasks.take();
                short[] buffer = task.getData();
                int readSize = task.getReadSize();
                int encodedSize = LameUtil.encode(buffer, buffer, readSize, mMp3Buffer);
                if (encodedSize > 0) {
                    try {
                        mFileOutputStream.write(mMp3Buffer, 0, encodedSize);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                shouldQuit = true;
            }
        }
    }

    private BlockingQueue<Task> mTasks= new ArrayBlockingQueue<Task>(50);


    private class Task {
        private short[] rawData;
        private int readSize;

        public Task(short[] rawData, int readSize) {
            this.rawData = rawData.clone();
            this.readSize = readSize;
        }
        public short[] getData() {
            return rawData;
        }
        public int getReadSize() {
            return readSize;
        }
    }
}
